<template>
  <el-container class="main-layout">
    <el-aside
      v-show="showDiv"
      :width="isCollapse ? '64px' : '240px'"
      class="main-aside"
    >
      <div class="logo-container">
        <span v-show="!isCollapse" class="logo-text"
          >普陀区环卫设施数据管理平台</span
        >
      </div>
      <el-scrollbar style="background-color: #283353">
        <el-menu
          :collapse="isCollapse"
          :default-active="activeMenu"
          class="el-menu-vertical"
          router
        >
          <el-menu-item
            v-for="item in leftRoutesRender"
            :key="item.path"
            :index="item.path"
            v-show="!item.meta?.hide"
            :class="isShowCustomClass(item)"
          >
            <el-icon><Odometer /></el-icon>
            <span>{{ item.meta.title }}</span>
            <span
              class="unread-count"
              v-if="unreadCount > 0 && item.path === '/audit'"
              >{{ unreadCount }}</span
            >
          </el-menu-item>
        </el-menu>
      </el-scrollbar>
    </el-aside>

    <el-container>
      <el-header v-show="showDiv" class="main-header">
        <div class="header-left">
          <el-icon class="trigger-icon" @click="toggleCollapse">
            <component :is="isCollapse ? 'Expand' : 'Fold'" />
          </el-icon>

          <el-menu
            :default-active="activeIndex"
            class="el-menu-demo"
            mode="horizontal"
            :ellipsis="false"
            @select="handleSelect"
          >
            <el-menu-item
              index="1"
              v-show="departments.permissions.includes('1')"
              >公共厕所</el-menu-item
            >
            <el-menu-item
              index="2"
              v-show="departments.permissions.includes('2')"
              >垃圾压缩站</el-menu-item
            >
            <el-menu-item
              index="3"
              v-show="departments.permissions.includes('3')"
              >可回收物点站场</el-menu-item
            >
            <el-menu-item
              index="4"
              v-show="departments.permissions.includes('4')"
              >环卫道班房</el-menu-item
            >
            <el-menu-item
              index="5"
              v-show="departments.permissions.includes('5')"
              >环卫停车场</el-menu-item
            >
            <el-menu-item
              index="6"
              v-show="departments.permissions.includes('6')"
              >系统管理</el-menu-item
            >
          </el-menu>
        </div>

        <div class="header-right">
          <div class="header-actions">
            <el-dropdown
              @command="handleCommand"
              trigger="click"
              :teleported="true"
            >
              <div class="user-info">
                <el-avatar
                  :size="32"
                  src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
                />
                <span class="username">{{ roles.name }}</span>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">
                    <el-icon><User /></el-icon>修改密码
                  </el-dropdown-item>
                  <el-dropdown-item divided command="logout">
                    <el-icon><SwitchButton /></el-icon>退出登录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </el-header>

      <el-main class="main-content" :class="{ 'full-screen': !showDiv }">
        <!-- <router-view v-slot="{ Component }">
          <transition name="fade" mode="out-in">
            <component :is="Component" />
          </transition>
        </router-view> -->
        <keep-alive :include="cacheTabs">
          <router-view class="page-main"></router-view>
        </keep-alive>
      </el-main>
    </el-container>

    <!-- 修改密码组件 -->
    <ChangePassword ref="changePasswordRef" />
  </el-container>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { useAppStore } from "@/stores/app";
import { getUnreadCount } from "@/utils/unread.js";
// import { useI18n } from "vue-i18n";
import { leftRoutes } from "@/router/left";
import ChangePassword from "@/components/ChangePassword.vue";
// 公共厕所 垃圾压缩站 可回收物点站场 环卫道班房 环卫停车场
const subMenuList = [
  "/publicToilet",
  "/garbageStation",
  "/recyclingStation",
  "/sanitationRoom",
  "/parkingLots",
];
const hideTopHeader = [
  "/screenManage",
  "/departmentManage",
  "/roleManage",
  "/userManage",
  "/operationLog",
];
const projectTableList = ref([
  "public_toilets",
  "garbage_stations",
  "recyclable_sites",
  "sanitation_rooms",
  "parking_lots",
]);
const router = useRouter();
const route = useRoute();
const isCollapse = ref(false);
const activeIndex = ref("0");
const appStore = useAppStore();
const changePasswordRef = ref(null);

const showMenuByType = ref("page"); // 是否显示 type 为 system 的菜单

const showDiv = computed(() => {
  // 当前路由不等于 '/screenManage' 时显示顶部和侧边栏
  return route.path !== "/screenManage";
});

const unreadCount = computed(() => appStore.getUnreadCount);

const userInfo = computed(() =>
  typeof appStore.userInfo === "object"
    ? appStore.userInfo
    : JSON.parse(appStore.userInfo)
);
// 角色权限 控制左侧菜单
const roles = computed(() => userInfo.value?.roles || {});
// 部门权限 控制顶部菜单
const departments = computed(
  () => userInfo.value?.departments || { permissions: "" }
);
const activeMenu = computed(() => route.path);
// 渲染左侧菜单
const leftRoutesRender = computed(() => {
  if (roles.value) {
    return leftRoutes
      .filter((item) => {
        return (
          roles.value[item.key] !== "" && item.meta.type == showMenuByType.value
        );
      })
      .map((item) => {
        return {
          ...item,
          key: item.key,
        };
      });
  }
  return leftRoutes;
});
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value;
};

const handleCommand = (command) => {
  switch (command) {
    case "logout":
      localStorage.removeItem("token");
      appStore.setUserInfo(null);
      localStorage.removeItem("userInfo");
      ElMessage.success("退出成功");
      router.push("/login");
      break;
    case "profile":
      changePasswordRef.value?.openDrawer();
      break;
  }
};

const handleSelect = (key) => {
  if (key == "6") {
    showMenuByType.value = "system";
    // 默认跳转到 leftRoutes 中 type 为 system 的第一个菜单
    router.push(leftRoutes.find((item) => item.meta.type === "system").path);
  } else {
    if (showMenuByType.value == "system") {
      showMenuByType.value = "page";
      router.push(leftRoutes.find((item) => item.meta.type === "page").path);
      return;
    }
    let isDataList = subMenuList.includes(route.path);
    if (isDataList) {
      router.push(subMenuList[Number(key) - 1]);
    } else {
      console.log(key, "我是key");
      router.replace({
        path: route.path,
        query: {
          type: key,
        },
      });
    }
    if (route.path !== "/audit") {
      let numKey = Number(key);
      getUnreadCount({
        project_table: projectTableList.value[numKey - 1],
        type: 0,
      });
    }
  }
  activeIndex.value = key;
};

watch(
  userInfo,
  () => {
    console.log(userInfo.value, "监听用户信息", route.path);
    if (userInfo.value) {
      let departments = userInfo.value.departments;
      if (departments.permissions != "") {
        let permissions = departments.permissions.split(",");
        activeIndex.value = permissions[0];
      } else {
        activeIndex.value = "0";
      }
    }
  },
  {
    immediate: true,
    deep: true,
  }
);
// 监听路由变化
watch(
  route,
  (newVal) => {
    let departments = userInfo.value.departments;
    // 重定向到第一个有权限的菜单
    let permissions = departments.permissions.split(",");
    if (newVal.path === "/dataList") {
      router.replace({
        path: subMenuList[Number(permissions[0]) - 1],
      });
      return;
    }
    // 根据当前路由设置选中状态
    if (subMenuList.includes(newVal.path)) {
      console.log(subMenuList.indexOf(newVal.path), "我是activeIndex");
      activeIndex.value = String(subMenuList.indexOf(newVal.path) + 1);
    }
    if (
      !hideTopHeader.includes(newVal.path) &&
      !subMenuList.includes(newVal.path)
    ) {
      let type = route.query.type || permissions[0];
      console.log(newVal.path, "我是newVal");
      router.replace({
        path: newVal.path,
        query: {
          type,
        },
      });
      activeIndex.value = String(type);
    }
  },
  {
    immediate: true,
    deep: true,
  }
);

const isShowCustomClass = (item) => {
  if (subMenuList.includes(route.path) && item.path == "/dataList") {
    return "is-active";
  }
  return "";
};
</script>

<style lang="scss" scoped>
.main-layout {
  min-height: 100vh;
}

.main-aside {
  background-color: var(--menu-background);
  transition: width 0.3s;
  overflow: hidden;
}

.logo-container {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 20px;
  color: white;
  background: var(--menu-background);
}

.logo-img {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  margin-right: 12px;
}

.logo-text {
  font-size: 15px;
  font-weight: 600;
  white-space: nowrap;
}

.main-header {
  background: var(--header-background);
  border-bottom: 1px solid var(--border-color);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 60px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.trigger-icon {
  font-size: 20px;
  cursor: pointer;
  color: var(--text-color-secondary);
}

.trigger-icon:hover {
  color: var(--primary-color);
}

.user-dropdown {
  cursor: pointer;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 0 4px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: rgba(0, 0, 0, 0.04);
}

.username {
  font-size: 14px;
  color: #fff;
}

.main-content {
  background: #fff;
  border: 12px solid #f0f2f5;
  box-sizing: border-box;
  padding: 0 12px;
}

.menu-item {
  margin: 4px 0;
  border-radius: 4px;
}

:deep(.el-menu) {
  border-right: none;
  background: transparent;
  color: #fff !important;
  .el-menu-item {
    color: #fff !important;
  }
  .el-menu-item:hover {
    background: rgba(0, 0, 0, 0.04);
  }
}

:deep(.el-menu-item.is-active) {
  background: var(--primary-color) !important;
  color: white !important;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.action-item {
  display: flex;
  align-items: center;
}

.action-button {
  font-size: 20px;
  color: var(--text-color-secondary);
  transition: color 0.3s;
  padding: 0 8px;
  height: 32px;
}

.action-button:hover {
  color: var(--primary-color);
}

.el-divider--vertical {
  height: 20px;
  margin: 0 12px;
}

// 隐藏原始单选框
:deep(.el-radio__original) {
  display: none !important;
}

// 移除单选框焦点样式
:deep(
    .el-radio:focus:not(.is-focus):not(:active):not(.is-disabled)
      .el-radio__inner
  ) {
  box-shadow: none !important;
}

// 全屏时主内容区样式
.full-screen {
  border: none !important;
  padding: 0 !important;
}

.unread-count {
  background-color: #f00;
  box-sizing: border-box;
  padding: 2px 4px;
  margin-left: 15px;
  color: #fff;
  min-width: 20px;
  height: 20px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
}
</style>
